//
//  ViewController.m
//  坦克大战
//
//  Created by 宗大丞 on 16/5/24.
//  Copyright © 2016年 Zong. All rights reserved.
//

#import "ViewController.h"
#import "Factory.h"
#import <AudioToolbox/AudioToolbox.h>
#import "XibUtil.h"
#import "PassViewViewController.h"
#import "WelcomeViewController.h"

@interface ViewController ()

@property (nonatomic, retain) UIView *mainView;//坦克活动界面.
@property (nonatomic, retain) UIView *controlView;//控制按钮界面.
@property (nonatomic, retain) Tank *mainTank;//???

/** 上下左右四个方向按钮及开火按钮. */
@property (nonatomic, retain) UIButton *upBtn;
@property (nonatomic, retain) UIButton *downBtn;
@property (nonatomic, retain) UIButton *leftBtn;
@property (nonatomic, retain) UIButton *rightBtn;
@property (nonatomic, retain) UIButton *fireBtn;

@property (nonatomic, retain) Factory *factory;
@property (nonatomic, retain) UILabel *info;//显示当前分数.
@property (nonatomic, retain) UILabel *zj;//主角光环字样.

@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGFloat minWidth;

@end


/** 刷新时间. */
double interval_refresh = 0.025;
int oneSeconeCount = 40;
double interval_tankMove = 0.35;
int baseTag = 100;
int fireTag = 1000;
static UIButton *_playBtn;
static NSTimer *_timer;

/** 是否显示欢迎界面. */
static bool welcomed = false;

/** 设置关卡. */
static int stage = 0;
static int totalStatge = 4;

/** 设置敌方坦克数量. */
static int badTankCount = 13;

/** 初始化几个坦克. */
int const count_tank_init = 3;

/** 设置无敌时间. */
int wuditime = 10;

CGFloat scale;//???

/** 当前坦克个数. */
int count_tank = count_tank_init;


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initData];
    [self initUI];
    [self initControlBtns];

}

- (void)initData {
    
    self.width = self.view.frame.size.width;
    self.height = self.view.frame.size.height;
    
    CGFloat mainViewWidth = self.width - 20;
    
    self.minWidth = mainViewWidth / 13 / 2;//游戏区域分为26块,按一下坦克移动一块.
}

#pragma mark - 游戏界面布局.
- (void)initUI {
    
    CGFloat mainViewWidth = self.width - margin_x * 2;
    
    self.view.backgroundColor = [UIColor greenColor];
    
    //设置游戏界面背景图.
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"4.jpg" ofType:nil]];
    [self.view addSubview:imgView];
    
    //设置显示坦克区域.
    self.mainView = [[UIView alloc] initWithFrame:CGRectMake(margin_x, margin_y, mainViewWidth, mainViewWidth)];
    self.mainView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.mainView];
    
    //设置主角光环.
    self.zj = [[UILabel alloc] initWithFrame:CGRectMake(-20, -10, 100, 40)];
    self.zj.text = @"主角光环";
    self.zj.textColor = [UIColor redColor];
    self.zj.tag = 2333;
    [_mainTank.imgView addSubview:self.zj];
    
    //初始化工厂(创建坦克,判断位置).
    self.factory = [Factory new];
    self.factory.tankFrame = CGRectMake(0, 0, self.minWidth * 2, self.minWidth * 2);
    self.factory.mainView = self.mainView;
    
    //显示分数Label.
    CGFloat btnWidth = 40;
    CGFloat marginTop = 40;
    
    self.info = [[UILabel alloc] initWithFrame:CGRectMake(mainViewWidth / 2, self.width - 20 + marginTop - 5, mainViewWidth / 2, btnWidth)];
    self.info.textAlignment = NSTextAlignmentLeft;
    self.info.textColor = [UIColor whiteColor];
    [self.info setFont:[UIFont fontWithName:@"Helvetica-BoldOblique" size:30]];
    [self.view addSubview:self.info];
    
    self.factory.info = self.info;
    
    
    //初始化坦克后,初始化timer.
    _timer = [NSTimer timerWithTimeInterval:interval_refresh target:self selector:@selector(refresh:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];//???
    
    CGPoint mc = self.mainView.center;
    self.mainTank = [self.factory createTank:TankTypeMain direction:TankDirectioneUp center:CGPointMake(mc.x - 100, mc.y + _mainView.frame.size.width / 2 - 60)];
    
    //创建地形图.
    XibUtil *util = [[XibUtil alloc] initWithMainView:self.mainView];
    for (Wall *wall in [util getWallsFromXib:@"Map0"]) {
        
        [self.mainView addSubview:wall.imgView];
        [self.mainView bringSubviewToFront:wall.imgView];
    }
    
    
    //分数前坦克小图标.
    UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(mainViewWidth / 2 - btnWidth, self.width - 20 + marginTop, 30, 30)];
    icon.image = [UIImage imageNamed:@"1048576_4"];
    [self.view addSubview:icon];
    
}

#pragma mark - 控制按钮布局.
- (void)initControlBtns {
    
    scale = [UIScreen mainScreen].bounds.size.width / 414;
    
    CGFloat mainViewWidth = self.width - 20 *scale;
    CGFloat margin = 10 * scale;
    CGFloat btnWidth = 40 * scale;
    CGFloat marginTop = 40 * scale;
    
    //创建控制区域视图.
    self.controlView = [[UIView alloc] initWithFrame:CGRectMake(10, 40 * scale + mainViewWidth, mainViewWidth, mainViewWidth)];
    [self.view addSubview:self.controlView];
    
    //分别添加各种按钮.
    [_controlView addSubview:[self createBtn:@"dir_left" frame:CGRectMake(margin, btnWidth + marginTop, btnWidth, btnWidth) tag:baseTag + TankDirectioneLeft]];
    
    [_controlView addSubview:[self createBtn:@"dir_right" frame:CGRectMake(margin + btnWidth * 2, btnWidth + marginTop, btnWidth, btnWidth) tag:baseTag + TankDirectioneRight]];
    
    [_controlView addSubview:[self createBtn:@"dir_up" frame:CGRectMake(margin + btnWidth, 0 + marginTop, btnWidth, btnWidth) tag:baseTag + TankDirectioneUp]];
    
    [_controlView addSubview:[self createBtn:@"dir_down" frame:CGRectMake(margin + btnWidth, btnWidth * 2 + marginTop, btnWidth, btnWidth) tag:baseTag + TankDirectioneDown]];
    
    [_controlView addSubview:[self createBtn:@"fire" frame:CGRectMake(_controlView.frame.size.width - margin - btnWidth * 2, btnWidth + marginTop, btnWidth * 2, btnWidth * 1.6) tag:fireTag]];

    _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _playBtn.frame = CGRectMake(self.controlView.frame.size.width - margin - btnWidth * 5, btnWidth + marginTop, btnWidth * 1.4, btnWidth * 1.4);
    [_playBtn addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
    [_playBtn setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
    [_playBtn setImage:[UIImage imageNamed:@"play"] forState:UIControlStateSelected];
    [_controlView addSubview:_playBtn];
}

#pragma mark - 创建按钮.
- (UIButton *)createBtn:(NSString *)title frame:(CGRect)frame tag:(int)tag {
    
    UIButton *button = [[UIButton alloc] initWithFrame:frame];
    [self.controlView addSubview:button];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:title] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont boldSystemFontOfSize:30];
    button.tag = tag;
    
    [button addTarget:self action:@selector(handleClick:) forControlEvents:UIControlEventTouchDown];//这不写TouchDown不能动.
    [button addTarget:self action:@selector(handleUp:) forControlEvents:UIControlEventTouchUpInside];
    
    
    return button;
}

#pragma mark - 按钮点击方法.
/** 方向按钮. */
- (void)handleClick:(UIButton *)button {
    
    if (fireTag != button.tag && !_playBtn.selected && ![Factory isGameover]) {
        
        self.mainTank.canMove = true;
        
        //button.tag - baseTag就是方向的枚举.
        self.mainTank.dir = button.tag - baseTag;
    }
    else {
        
        for (Bullet *bullet in self.mainTank.bullets) {
            
            if (!bullet.canMove) {
                
                bullet.canMove = true;
                break;
            }
        }
    }
}

- (void)handleUp:(UIButton *)button {
    
    if (fireTag != button.tag) {
        
        self.mainTank.canMove = false;
    }
    else {
        
        
    }
}
/** 开始按钮. */
- (void)play:(UIButton *)button {
    
    if (![Factory isGameover]) {
        
        _playBtn.selected = !_playBtn.selected;
        
        if (_playBtn.selected) {
            
            _timer.fireDate = [NSDate distantFuture];
        }
        else {
            
            _timer.fireDate = [NSDate distantPast];
        }
    }
}

#pragma mark - 暂停按钮.
+ (void)pauseGame {
    
    _playBtn.selected = YES;
    _timer.fireDate = [NSDate distantFuture];
}

#pragma mark - 添加声音.
- (void)playingSoundEffectWith:(NSString *)fileName {
    
    NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:nil]];
    
    if (fileURL != nil) {
        
        SystemSoundID theSoundID;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)fileURL,  &theSoundID);
        AudioServicesPlaySystemSound(theSoundID);
    }
}

#pragma mark - 产生坏坦克.
- (void)randBadTank {
    
    [self.factory randomBadTank:bornLocation_left];
    [self.factory randomBadTank:bornLocation_middle];
    [self.factory randomBadTank:bornLocation_right];
}

int count_time = 0;
int hideZJ = 0;
#pragma mark - 刷新主坦克.
- (void)refresh:(NSTimer *)timer {
    
    count_time ++;
    
    int arcN = arc4random() % 20;//随机秒数后产生新坦克,但是要大于.
    
    if (count_tank < badTankCount && count_time > oneSeconeCount * 5 && arcN < 2) {
        
        count_time = 0;
        
        if ([self.factory randomBadTank: -1]) {
            
            count_tank ++;
        }
        
        if (arcN == 1) {
            
            if ([self.factory randomBadTank: -1]) {
                
                count_tank ++;
            }
        }
    }
    
    if (!self.zj.isHidden) {
        
        hideZJ ++;
    }
    
    if (hideZJ >= wuditime * oneSeconeCount) {
        
        hideZJ = 0;
        self.zj.hidden = YES;
        [self.zj removeFromSuperview];
    }
    
    [self pass];
    
    //创建新的主坦克,不加外层判断有两个坦克.
    if (self.mainTank.life > 0 && self.mainTank.isDeath) {
    
        if (self.mainTank.life > 0) {
            
            CGPoint mc = self.mainView.center;
            CGFloat width = self.mainView.frame.size.width;
            NSInteger life = self.mainTank.life - 1;
            
            self.mainTank = [self.factory createTank:TankTypeMain direction:TankDirectioneUp center:CGPointMake(mc.x - 100, mc.y + width / 2 - 60)];
            self.mainTank.life = life;
            self.info.text = [NSString stringWithFormat:@"我方:%ld", self.mainTank.life];
            
            [self zjgh];
        }
    }
    
    if (self.mainTank.life <= 0 && self.mainTank.isDeath) {
        
        [Factory setIsGameover:true];
    }
    
    [self.mainTank move:self.mainTank.dir timer:_timer];
    
    for (Bullet *bullet in self.mainTank.bullets) {
        
        [self.mainTank fire:bullet timer:_timer];
    }
    
    [self randTankMoveAndFire];
}

#pragma mark - 过关或结束.
static int stageCount = 1;
- (void)pass {
    
    if ([Factory isGameover]) {
        
        sleep(2.0);
        [self excessive:@"GAME OVER"];
    }
    
    if (count_tank >= badTankCount && [Factory instanceOfBadTankArray].count == 0 && ![Factory isBorining] && ![Factory isGameover]) {
        
        [self excessive:[NSString stringWithFormat:@"SCENARIO:%d", ++stageCount]];
    }
    
}

#pragma mark - 无敌???
- (void)zjgh {
    
    [self.mainTank.imgView addSubview:self.zj];
    
    hideZJ = 0;
    self.zj.hidden = NO;
}

#pragma mark - 坦克随机移动.
- (void)randTankMoveAndFire {
    
    if (badTankStop) {
        
        stopCount ++;
        
        if (stopCount >= oneSeconeCount * 6) {
            
            badTankStop = false;
            stopCount = 0;
        }
        
        return;
    }
    
    for (Tank *tank in [Factory instanceOfBadTankArray]) {
        
        //1-100变换方向的概率.
        NSInteger changeDir = arc4random() % 100 + 1;
        
        //有%5的概率不移动,有%75的概率改变方向.
        if (changeDir > 95) {
            
            tank.canMove = false;
            tank.dir = 1 << arc4random() % 4;
        }
        else {
            
            tank.canMove = true;
            [tank move:tank.dir timer:_timer];
        }
        
        //百分之2的概率开火.
        if (changeDir < 4 && !tank.isDeath && !tank.bobming) {
            
            tank.bullets.firstObject.canMove = true;//???
        }
        
        [tank fire:tank.bullets.firstObject timer:_timer];
    }
}

#pragma mark - 过度画面.
- (void)excessive:(NSString *)tip {
    
    PassViewViewController *passVC = [PassViewViewController new];
    
    passVC.tip = tip;
    passVC.viewController = self;
    
    _timer.fireDate = [NSDate distantFuture];
    [Factory clearAll];
    
    CATransition *animation = [CATransition animation];
    animation.duration = 2.5;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromRight;
    [self.view.window.layer addAnimation:animation forKey:nil];
    [self presentViewController:passVC animated:YES completion:nil];
}

#pragma mark - 敌方停6秒.
static bool badTankStop = false;
int stopCount = 0;
+ (void)stopBadTankIn6s {
    
    badTankStop = true;
    stopCount = 0;
}

#pragma mark - 游戏开始.
- (void)restart {
    
    [Factory clearAll];
    [Factory setIsGameover:false];
    _mainTank.life = 3;
    stage = -1;
    stageCount = 1;
    _mainTank.level = 0;
    count_tank = count_tank_init;
}

#pragma mark - 视图将要显示.
-(void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    if (!welcomed) {
        
        welcomed = true;
        
        [self presentViewController:[WelcomeViewController new] animated:YES completion:nil];
        
        [self restart];
        
        _timer.fireDate = [NSDate distantFuture];
        
        return;
    }
    
    _timer.fireDate = [NSDate distantPast];
    
    [self playingSoundEffectWith:@"start.wav"];
    
    if (![Factory isBorining] && ![Factory isGameover]) {
        
        stage ++;
        
        if (stage >= totalStatge) {
            
            stage = 0;
        }
        
        count_tank = count_tank_init;
        
        [self randBadTank];
        
        CGPoint mc = self.mainView.center;
        CGFloat width = self.mainView.frame.size.width;
        NSInteger life = self.mainTank.life;
        int level = self.mainTank.level;
        
        self.mainTank = [self.factory createTank:TankTypeMain direction:TankDirectioneUp center:CGPointMake(mc.x - 100, mc.y + width / 2 - 60)];
        
        [self zjgh];
        
        self.mainTank.life = life;
        self.mainTank.level = level;
        
        self.mainTank.level = 3;//开挂开挂.
        
        XibUtil *util = [[XibUtil alloc] initWithMainView:self.mainView];
        for (Wall *wall in [util changeMap:[NSString stringWithFormat:@"Map%d", stage]]) {
            
            [self.mainView addSubview:wall.imgView];
            [self.mainView bringSubviewToFront:wall.imgView];
        }
    }
    
    self.info.text = [NSString stringWithFormat:@"我方:%ld", self.mainTank.life];
}

-(void)viewDidDisappear:(BOOL)animated {
    
    [ViewController pauseGame];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end









































































